package com.heima.app.gateway.filter;

import com.heima.app.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
//@Order(0) 和实现Ordered接口是效果一样
//GlobalFilter  全局过滤器
public class AuthorizeFilter implements Ordered , GlobalFilter {

    //值越小 过滤器的优先级越高
    @Override
    public int getOrder() {
        return 0;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.通过ServerWebExchange获取request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //2.校验请求url是否包含login  判断是否是登陆请求  如果是则放行
        if(request.getURI().getPath().contains("/login")){
            return chain.filter(exchange);//放行
        }

        //3.从请求头中获取token令牌
        String token = request.getHeaders().getFirst("token");

        //4.并校验令牌   是否为空,是否正确
        if(StringUtils.isBlank(token)){
            //返回无权限 401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();//请求不在往后端微服务路由
        }
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            int i = AppJwtUtil.verifyToken(claimsBody);
            if(i==1 ||i==2){
                //说明令牌过期
                //返回无权限 401
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();//请求不在往后端微服务路由
            }


            //解析jwt令牌中的id，放入请求头  key为userId，然后在往后端微服务转发
            // 从claimsBody获取 id  存入header，然后路由到后端微服务
            Integer id = (Integer)claimsBody.get("id");
            ServerHttpRequest serverHttpRequest = request.mutate().header("userId", String.valueOf(id)).build();
            //重置header
            exchange.mutate().request(serverHttpRequest).build();


        } catch (Exception exception) {
            //返回无权限 401
            exception.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();//请求不在往后端微服务路由
        }

        //5.放行
        return chain.filter(exchange);
    }
}
